<!--
 * @Description：基础管理--菜单管理
 * @author： wlj
 * @date： 2025/04/24 10:52:16
!-->
<template>
  <div class="app-container">
    <el-form :inline="true" @submit.native.prevent>
      <el-form-item label="状态">
        <el-select v-model="listQuery.status" clearable placeholder="全部" @change="handleResetPage">
          <el-option
            v-for="item in isStateOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="菜单名称">
        <el-input v-model="listQuery.name" placeholder="请输入菜单名称,回车搜索" style="width: 300px" @keyup.enter.native="handleResetPage">
          <el-button slot="append" icon="el-icon-search" @click="handleResetPage" />
        </el-input>
      </el-form-item>
      <!-- <el-button type="danger" @click="batchDelete()">批量删除</el-button> -->
      <!-- <el-button type="danger" @click="batchStop()">批量停用</el-button>
      <el-button type="success" @click="batchOpen()">批量启用</el-button> -->
      <el-button type="primary" @click="handleCreate()">新增</el-button>
    </el-form>
    <el-card class="tree-card" shadow="never" style="height: 750px; width: 254px; float: left">
      <el-tree
        ref="tree"
        :data="menu_tree_data"
        :props="treeProps"
        accordion
        node-key="id"
        highlight-current
        :default-expanded-keys="[tree_default_check]"
        :default-checked-keys="[tree_default_check]"
        @node-click="handleTreeClick"
      />
    </el-card>
    <el-row style="float: left; margin-left: 10px; width: calc(100% - 264px)">
      <el-col :span="24">
        <el-table
          v-loading="listLoading"
          :data="list"
          border
          fit
          stripe
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" align="center" width="55" />
          <el-table-column label="名称" prop="name" />
          <el-table-column label="路由" prop="router" />
          <el-table-column label="组件名称" prop="componentName" />
          <el-table-column label="组件路径" prop="component" />
          <el-table-column label="菜单图标" prop="icon" />
          <el-table-column label="状态" width="110" align="center">
            <template slot-scope="scope">
              {{ statusFilter(scope.row) }}
            </template>
          </el-table-column>
          <el-table-column label="排序" prop="sort" align="center" width="80" />
          <el-table-column width="100" label="操作" align="center">
            <template slot-scope="scope">
              <el-dropdown class="operation-style">
                <span class="el-dropdown-link">
                  操作<i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item @click.native="handleInfo(scope.row)">查看</el-dropdown-item>
                  <el-dropdown-item @click.native="handleEdit(scope.row)">编辑</el-dropdown-item>
                  <el-dropdown-item @click.native="handleDelete(scope.row)">删除</el-dropdown-item>
                  <el-dropdown-item @click.native="handleChangeState(scope.row)">{{ scope.row.status === 1 ? '停用' : '启用' }}</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <div v-if="count > 0">
          <pagination
            :total="count"
            layout="total,sizes, prev, pager, next, jumper"
            :page.sync="listQuery.pageSort.pageIndex"
            :limit.sync="listQuery.pageSort.pageSize"
            @pagination="search"
          />
        </div>
      </el-col>
    </el-row>
    <el-dialog
      v-loading.fullscreen.lock="fullscreenLoading"
      :title="dialogFormStatus"
      :visible.sync="dialogFormVisible"
      form
      width="40%"
      destroy-on-close
      lock-scroll
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <el-form
        ref="form"
        :disabled="type === 'info'"
        :rules="rules"
        :model="form"
        label-width="110px"
        @submit.native.prevent
      >
        <el-form-item v-if="type === 'add'" label="父级菜单名称">
          <el-input v-model.trim="form.parentName" placeholder="顶级菜单" disabled />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model.trim="form.name" @input="handleInput" />
        </el-form-item>
        <el-form-item label="编码" prop="code">
          <el-input v-model.trim="form.code" :disabled="type === 'edit'" />
        </el-form-item>
        <el-form-item label="链接" prop="router">
          <el-input v-model.trim="form.router" placeholder="/或/#/后的路径如：/basic/menu，父级菜单填/basic" />
        </el-form-item>
        <el-form-item label="组件名称" prop="componentName">
          <el-input v-model.trim="form.componentName" placeholder="路由组件的名称，请勿重复" />
        </el-form-item>
        <el-form-item label="组件路径" prop="component">
          <el-input v-model.trim="form.component" placeholder="@/views下的路径如：/basic/menu，父级菜单填Layout" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model.trim="form.sort" />
        </el-form-item>
        <el-form-item label="菜单图标" prop="icon">
          <el-input v-model.trim="form.icon" placeholder="仅一级菜单填写图标名" />
        </el-form-item>
        <el-form-item label="路由类型" prop="type">
          <el-radio-group v-model="form.type" v-removeAriaHidden>
            <el-radio :label="0">节点</el-radio>
            <el-radio :label="1" disabled>功能</el-radio>
            <el-radio :label="2" disabled>按钮</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status" v-removeAriaHidden>
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCancelDialog()">取 消</el-button>
        <el-button type="primary" @click="submitForm('form')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { selectModule, moduleTree, deleteModule, enabledModule, disableModule, alterModule, addModule } from '@/api/basic/module'
export default {
  name: 'BasicModule',
  data() {
    return {
      fullscreenLoading: false,
      dialogFormStatus: '',
      type: '', // 查看详情
      dialogFormVisible: false,
      isStateOptions: [
        { value: 1, label: '启用' },
        { value: 0, label: '停用' }
      ],
      // 搜索返回数据
      listQuery: {
        name: '',
        pageSort: {
          pageIndex: 1,
          pageSize: 20
        },
        parentName: '',
        parentCode: 0,
        status: ''
      },
      list: [],
      count: 0, // 总数
      multipleSelection: [], // 多选数据 （暂未使用）
      listLoading: false,
      menu_tree_data: [],
      tree_default_check: '', // 树被选中的数据
      form: {
        // 新增和编辑数据存放
        code: '',
        name: '',
        parentCode: 0,
        sort: '',
        component: '',
        componentName: '',
        router: '',
        icon: '',
        type: 0,
        status: 1,
        parentName: '',
        platform: 'ADMIN'
      },
      rules: {
        name: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
        router: [{ required: true, message: '请输入路由地址', trigger: 'blur' }],
        component: [{ required: true, message: '请输入组件路径', trigger: 'blur' }],
        componentName: [{ required: true, message: '请输入组件名称', trigger: 'blur' }],
        sort: [{ required: true, message: '请输入排序', trigger: 'blur' }]
      },
      treeProps: {
        label: 'name'
      }
    }
  },
  created() {
    this.search()
  },
  methods: {
    statusFilter(row) {
      if (row.status === 1) return '启用'
      else if (row.status === 0) return '停用'
      else return ' '
    },
    // 列表搜索方法
    search() {
      this.listLoading = true
      this.initMenuTree()
      selectModule(this.listQuery).then((res) => {
        this.list = res.data.rows
        if (this.list) {
          this.list.forEach((item) => {
            item.parentCode = this.listQuery.parentCode
          })
        }
        this.count = res.data.total
        this.listLoading = false
      })
    },
    // 获取菜单树数据
    initMenuTree() {
      moduleTree('ADMIN').then((res) => {
        if (res.success) {
          this.menu_tree_data = [
            {
              id: 0,
              name: '菜单',
              children: res.data
            }
          ]
          this.$nextTick(() => {
            this.tree_default_check = this.tree_default_check ? this.tree_default_check : 0
            this.$refs.tree.setCurrentKey(this.tree_default_check)
          })
        } else this.$message.error(res.message)
      })
    },
    handleCreate() {
      // 点击新增
      this.type = 'add'
      this.dialogFormStatus = '新增'
      this.dialogFormVisible = true
    },
    // 新增--》名称输入框事件
    handleInput() {
      if (this.type === 'add') {
        this.form.name = this.inputPInYinCode(this.form.name).name
        this.form.code = this.inputPInYinCode(this.form.name).code
      }
    },
    // 点击查看菜单
    handleInfo(row) {
      this.form = {
        name: row.name,
        router: row.router,
        component: row.component,
        componentName: row.componentName,
        icon: row.icon,
        sort: row.sort,
        status: row.status,
        code: row.code,
        parentCode: row.parentCode,
        type: row.type
      }
      this.dialogFormStatus = '查看'
      this.type = 'info'
      this.dialogFormVisible = true
    },
    // 点击编辑菜单
    handleEdit(row) {
      this.form = {
        code: row.code,
        name: row.name,
        router: row.router,
        component: row.component,
        componentName: row.componentName,
        icon: row.icon,
        sort: row.sort,
        status: row.status,
        parentCode: row.parentCode,
        parentName: this.form.parentName,
        type: row.type,
        platform: row.platform
      }
      this.dialogFormStatus = '编辑'
      this.type = 'edit'
      this.dialogFormVisible = true
    },
    // 点击确定新增/编辑
    handleConfirm() {
      this.fullscreenLoading = true
      if (this.type === 'edit') {
        // 编辑
        const _editFromData = {
          code: this.form.code,
          component: this.form.component,
          componentName: this.form.componentName,
          icon: this.form.icon,
          status: this.form.status,
          type: this.form.type,
          name: this.form.name,
          parentCode: this.form.parentCode,
          router: this.form.router,
          sort: this.form.sort
        }
        alterModule(_editFromData).then((res) => {
          this.$message({ message: res.message || '编辑成功', type: 'success' })
          this.search()
          this.handleCancelDialog()
          this.fullscreenLoading = false
        }).catch(() => {
          this.fullscreenLoading = false
        })
        // 新增
      } else if (this.type === 'add') {
        const _addFromData = {
          component: this.form.component,
          componentName: this.form.componentName,
          icon: this.form.icon,
          status: this.form.status,
          type: this.form.type,
          name: this.form.name,
          code: this.form.code,
          parentCode: this.form.parentCode,
          parentName: this.form.parentName,
          router: this.form.router,
          sort: this.form.sort,
          platform: this.form.platform
        }
        console.log('_addFromData: ', _addFromData)
        addModule(_addFromData).then((res) => {
          if (res.success) {
            this.$message({ message: res.message || '新增成功', type: 'success' })
            this.search()
            this.handleCancelDialog()
            this.fullscreenLoading = false
          }
        }).catch(() => {
          this.fullscreenLoading = false
        })
      } else {
        this.fullscreenLoading = false
        this.handleCancelDialog()
      }
    },
    // 对话框的取消显示
    handleCancelDialog() {
      this.dialogFormVisible = false
      this.form = {
        id: undefined,
        code: '',
        name: '',
        sort: '',
        component: '',
        componentName: '',
        router: '',
        icon: '',
        type: 0,
        status: 1,
        parentCode: this.form.parentCode,
        parentName: this.form.parentName,
        platform: 'ADMIN'
      }
    },
    // 删除菜单
    handleDelete(row) {
      // 单个删除
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.doDelete([row.code])
      }).catch(() => {})
    },
    // 停启用状态切换
    handleChangeState(row) {
      const text = row.status === 0 ? '启用' : '停用'
      this.$confirm('此操作将' + text + ', 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (row.status === 1) {
        // 启用状态
          this.doChangeState([row.code], 0)
        } else if (row.status === 0) {
          this.doChangeState([row.code], 1)
        }
      }).catch(() => {})
    },
    // 批量删除
    // batchDelete() {
    //   if (this.multipleSelection.length === 0) {
    //     this.$message({ message: '请选择需要删除的行！', type: 'warning' })
    //     return
    //   }
    //   this.$confirm('确定删除选定的行么?', '提示', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     type: 'warning'
    //   })
    //     .then(() => {
    //       const ids = []
    //       this.multipleSelection.forEach((row) => {
    //         ids.push(row.no)
    //       })
    //       this.doDelete(ids)
    //     })
    //     .catch(() => {})
    // },
    // 执行删除操作
    doDelete(uids) {
      deleteModule(uids).then((res) => {
        if (res.success) {
          this.$message({ message: '删除成功', type: 'info' })
          this.search()
        } else this.$message.error(res.message)
      })
    },
    // // 批量停用
    // batchStop() {
    //   if (this.multipleSelection.length === 0) {
    //     this.$message({ message: '请选择需要停用的行！', type: 'warning' })
    //     return
    //   }
    //   this.$confirm('确定停用选定的行吗？', '提示', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     type: 'warning'
    //   })
    //     .then(() => {
    //       const ids = []
    //       this.multipleSelection.forEach((row) => {
    //         ids.push(row.no)
    //       })
    //       this.doChangeState(ids, 0)
    //     })
    //     .catch(() => {
    //       this.$message.error('停用失败')
    //     })
    // },
    // // 批量启用
    // batchOpen() {
    //   if (this.multipleSelection.length === 0) {
    //     this.$message({ message: '请选择需要启用的行！', type: 'warning' })
    //     return
    //   }
    //   this.$confirm('确定启用选定的行吗？', '提示', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     type: 'warning'
    //   })
    //     .then(() => {
    //       const ids = []
    //       this.multipleSelection.forEach((row) => {
    //         ids.push(row.no)
    //       })
    //       this.doChangeState(ids, 1)
    //     })
    //     .catch(() => {
    //       this.$message.error('启用失败')
    //     })
    // },
    // 执行批量改变状态
    doChangeState(ids, status) {
      if (status === 1) {
        // 执行启用
        enabledModule(ids).then((res) => {
          if (res.success) {
            this.$message({ message: '启用成功', type: 'success' })
            this.search()
          } else this.$message.error(res.message)
        })
      } else if (status === 0) {
        // 执行禁用
        disableModule(ids).then((res) => {
          if (res.success) {
            this.$message({ message: '停用成功', type: 'info' })
            this.search()
          } else this.$message.error(res.message)
        })
      }
    },
    // 保存多选数据 （暂未使用）
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleTreeClick(data, node, dom) {
      // 树的点击
      // console.log('方法：handleTreeClick，打印：当前点击节点数据', data, '当前点击节点Node', node)
      this.tree_default_check = data.id
      this.form.parentCode = data.id
      this.form.parentName = data.id === 0 ? null : data.name
      this.listQuery.parentCode = data.id
      this.listQuery.pageSort.pageIndex = 1
      if (!node.isLeaf) {
        this.search()
      }
    },
    // 表单验证
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.handleConfirm()
        } else {
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    // 切换搜索条件时，页码重置
    handleResetPage() {
      this.listQuery.pageSort.pageIndex = 1
      this.search()
    }
  }
}
</script>
